import _set from 'lodash/set'
import _isEmpty from 'lodash/isEmpty'

export const changeTreeItem = (tree, func) => {
  const suit = (_tree) => {
    return _tree.map((it) => {
      if (it.children && it.children.length) {
        it.children = suit(it.children)
      }
      it = func(it)
      return it
    })
  }
  return !_isEmpty(tree) ? suit(tree) : []
}

function _basePath (path) {
  if (Array.isArray(path)) return path
  return path.replace(/\[/g, '.').replace(/\]/g, '').split('.')
}

// function _set (object, path, value) {
//   if (typeof object !== 'object') return object
//   _basePath(path).reduce((o, k, i, _) => {
//     if (i === _.length - 1) {
//       o[k] = value
//       return null
//     } else if (k in o) {
//       return o[k]
//     } else {
//       o[k] = /^[0-9]{1,}$/.test(_[i + 1]) ? [] : {}
//       return o[k]
//     }
//   }, object)
//   return object
// }

function changeObjectToParams (val) {
  let obj = {}
  for (const i in val) {
    const it = val[i]
    const key = i
    const arr = key.split('.')

    if (arr.length >= 2) {
      _set(obj, key, it)
    } else {
      obj[key] = it
    }
  }
  return obj
}

function uuid () {
  var temp_url = URL.createObjectURL(new Blob())
  var uuid = temp_url.toString()
  URL.revokeObjectURL(temp_url)
  return uuid.substr(uuid.lastIndexOf('/') + 1)
}

function changeObjToTree (_obj) {
  const func = (obj) => {
    let arr = []
    for (const i in obj) {
      if (Object.prototype.toString.call(obj[i]) === '[object Object]') {
        let children = func(obj[i])
        arr.push({
          parameterKey: i,
          selfType: obj[i]._selfType,
          jsonKey: uuid(),
          selfPath: obj[i].path,
          ...children.length > 0 ? { children } : {}
        })
      }
    }
    return arr
  }
  return func(_obj)
}

export function analysisJson (json) {
  let obj = {}
  const func = (_json, keyName) => {
    if (Object.prototype.toString.call(_json) === '[object Object]') {
      obj[`${keyName}`] = { _selfType: 'object', path: `${keyName}` }
      for (const i in _json) {
        func(_json[i], `${keyName}.${i}`)
      }
    }

    if (Array.isArray(_json)) {
      if (typeof _json[0] == 'string') {
        obj[keyName] = { _selfType: 'array-string', path: `${keyName}` }
      } else {
        func(_json[0], keyName)
        obj[keyName] = { _selfType: 'array-object', path: `${keyName}` }
      }
    }

    if (['string', 'boolean', 'number'].includes(typeof _json)) {
      obj[keyName] = { _selfType: typeof _json, path: `${keyName}` }
    }
  }

  func(json, 'xx')

  const { xx } = changeObjectToParams(obj)
  return changeObjToTree(xx)
}

export function isJSON (str) {
  if (typeof str == 'string') {
    try {
      JSON.parse(str)
      return true
    } catch (e) {
      return false
    }
  }
}

export function parseSearchArgs (url) {
  let rst = {}
  if (url.indexOf('?') != -1) {
    let str = url.substr(1)
    let parts = str.split('&')
    for (let i = 0; i < parts.length; i++) {
      rst[parts[i].split('=')[0]] = decodeURI(parts[i].split('=')[1])
    }
  }
  return rst
}

export function treeToList (data = [], delChild = true) {
  let resData = []
  for (let obj of data) {
    let child = obj.children
    if (delChild) {
      delete obj.children
    }
    resData.push({ ...obj })
    if (child && child.length > 0) {
      resData = [...resData, ...treeToList(child, delChild)]
    }
  }
  return resData
}

export function delNullChild (_obj) {
  const func = (obj) => {
    return obj.map(it => {
      if (!_isEmpty(it.children)) {
        return {
          ...it,
          returnType: _isEmpty(it.returnType) ? undefined : it.returnType,
          children: func(it.children)
        }
      } else {
        const { children, ...ohter } = it
        return ohter
      }
    })
  }
  return _isEmpty(_obj) ? [] : func(_obj)
}